import 'dart:convert';
import 'dart:io';
import 'dart:math';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:get/route_manager.dart';
import 'package:launch_review/launch_review.dart';
import 'package:share_fit/app/controllers/base/base_controller.dart';
import 'package:share_fit/app/helper/ext/tr_ext.dart';
import 'package:share_fit/app/helper/storage_helper.dart';
import 'package:share_fit/app/tools/app_const.dart';
import 'package:share_fit/app/tools/app_util.dart';
import 'package:share_fit/app/tools/color_const.dart';
import 'package:share_fit/app/tools/log_utils.dart';
import 'package:share_fit/app/ute/uteped_config.dart';
import 'package:share_fit/app/ute/uteped_const.dart';
import 'package:share_fit/generated/locales.g.dart';

import 'update_view.dart';

class LaunchLogic extends BaseController {

  // static String CHECK_UPDATE_URL = 'https://mock.mengxuegu.com/mock/606c0cb6e34b2e50a355cda6/xx/update';
  static String CHECK_UPDATE_URL = 'https://watchapp.wiodo.tech/app/app_upgrade.json';
  static String M_googlePlayPlugin = "googlePlayPlugin";

  Future<dynamic> checkUpdate() async {
    print("launch page start... ");

    // Map appInfoMap = await UTEPedConfig.instance.getAppInfo();
    final dio = Dio();
    dio.options.connectTimeout = Duration(seconds: 10);
    dio.options.contentType = 'application/json';
    dio.interceptors.add(LogInterceptor(requestBody: true, responseBody: true));
    try {
      Response response = await dio.get(CHECK_UPDATE_URL);
      Map map = jsonDecode('$response');
      if(map.containsKey('app_info')) {
        for (var mapItem in map["app_info"]) {
          if(Platform.isAndroid && mapItem['platform']=='android') {
            return mapItem;
          } else if(Platform.isIOS && mapItem['platform']=='ios') {
            return mapItem;
          }
        }
      }
    } catch (e) {
      // if(e is DioException && e.response!=null) {
      //   return e.response;
      // }
      return 0;
    }
    // route();
    return 0;
  }

  bool compareVersions(String newVersion, String oldVersion) {
    if(newVersion.isEmpty || oldVersion.isEmpty) {
      return false;
    }
    int newVer, oldVer;
    var newList = newVersion.split('.');
    var oldList = oldVersion.split('.');
    if(newList.isEmpty || oldList.isEmpty) {
      return false;
    }

    for(int i=0; i<newList.length; i++) {
      newVer = int.parse(newList[i]);
      oldVer = int.parse(oldList[i]);
      if(newVer>oldVer) {
        return true;
      }
    }
    return false;
  }

  void toNextPage() {
    int startTime = DateTime.now().millisecondsSinceEpoch;
    checkUpdate().then((value) {
      logger.d('check update $value');
      int newTime = DateTime.now().millisecondsSinceEpoch;
      int delay = max(0, (3000 - (newTime - startTime)) ~/ 1000);

      /// 弹窗提示升级
      if (value is int && value == 0) {
        Future.delayed(Duration(seconds: delay), () {
          route();
        });
      } else {
        if (value.containsKey('needUpdate')) {
          int needUpdate = value['needUpdate'];
          String platform = value['platform'];
          String updateUrl = value['updateUrl'];
          String updateVersion = value['updateVersion'];
          String updateDes = value['updateDes'];
          Map appInfo =
              read(UTEPedConst.keyAppInfo, defaultValue: [], global: true);
          if (compareVersions(updateVersion, appInfo['versionName'])) {
            showDialog(
                context: Get.overlayContext!,
                barrierDismissible: false,
                builder: (BuildContext context) {
                  return UpdateDialog(
                      newVersion: updateVersion,
                      updateDes: updateDes,
                      callback: (value) {
                        if (value == 0) {
                          gotoStore(platform, updateUrl);
                        } else {
                          if (needUpdate == 0) {
                            Future.delayed(Duration(seconds: delay), () {
                              route();
                            });
                          } else {
                            exit(0);
                          }
                        }
                      });
                });
          } else {
            Future.delayed(Duration(seconds: delay), () {
              route();
            });
          }
        } else {
          Future.delayed(Duration(seconds: delay), () {
            route();
          });
        }
      }
    });
  }

  void route() {
    bool loginState = read('login_state', defaultValue: false, global: true);
    bool isSkip = read('login_skip', defaultValue: false, global: true);
    if(loginState) {
      int expireTimeSec = read('expire_time_sec', defaultValue: 0, global: true);
      if(expireTimeSec>(DateTime.now().millisecondsSinceEpoch/1000).round()) {
        Get.offNamed('/main');
        return;
      }
    }
    if(isSkip) {
      Get.offNamed('/main');
      return;
    }
    Get.offNamed('/login', arguments: {'toMainPage': false});
  }

  void gotoStore(String platform, String appId) async {
    if (platform=='android') {
      // Map appInfoMap = await UTEPedConfig.instance.getAppInfo();
      // _openGooglePlay(appInfoMap['packageName']);
      LaunchReview.launch(androidAppId: appId);
    } else if (platform=='ios') {
      // _openAppStore();
      LaunchReview.launch(iOSAppId: appId);
    }
  }

  void _openGooglePlay(String packageName) async {
    var info = await dRemoteReqAsync(M_googlePlayPlugin, {'type': packageName});
    print('openGooglePlay:$info');
  }

  void _openAppStore() async {

  }

  @override
  String getRemotePath() {
    return 'upgrade';
  }

  @override
  void initState() {

  }

  void _requestPermissions() {
    AppUtil.requestPermissions().then((value) => {
      toNextPage()
    });
  }

  @override
  void onReady() {
    super.onReady();
    var prominentAccept = StorageHelper.read(AppConst.prominentAccept, defaultValue: false);
    if (Platform.isAndroid && !prominentAccept) {
      Get.defaultDialog(
          title: LocaleKeys.info.ts,
          textConfirm: LocaleKeys.accept.ts,
          textCancel: LocaleKeys.deny.ts,
          buttonColor: ColorConst.accentColor,
          middleText: LocaleKeys.prominentMessage.ts,
          barrierDismissible: false,
          onConfirm: () => {
            StorageHelper.save(AppConst.prominentAccept, true),
            Get.back(),
            _requestPermissions()
          },
          onCancel: () => {
            Get.back(),
            _requestPermissions()
          });
    }
    else {
      toNextPage();
    }
  }

  @override
  void onRemoteEvent(event, method) {
    // TODO: implement onRemoteEvent
  }
}
